﻿using DTOs;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RBAC.Domain;
using RBAC.Domain.Service.Impl;
using RBAC.Domain.Service.Interfae;
using RBACDuYaJun.Api.Appliction.Command.UserCommand;
using RBACDuYaJun.Api.Dtos;
using RBACDuYaJun.Api.Extensions;
using System.IdentityModel.Tokens.Jwt;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace RBACDuYaJun.Api.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Authorize]//（JWT）
    [ApiController]
    public class UserController : ControllerBase
    {
      private readonly IConfiguration configuration;
        /// <summary>
        /// 利用IMediator
        /// </summary>
        private readonly IMediator _mediator;
        /// <summary>
        /// 用户服务层
        /// </summary>
        protected readonly IUserService _userServices;
        /// <summary>
        /// 省份服务层
        /// </summary>
        protected readonly IProvinceService _provinceServices;
        /// <summary>
        /// 所在市服务层
        /// </summary>
        protected readonly ICityService _cityServices;
        /// <summary>
        /// 所在县服务层
        /// </summary>
        protected readonly ICountryService _countryServices;
        /// <summary>
        /// 角色服务层
        /// </summary>
        private readonly IRoleService _roleServices;
        /// <summary>
        /// 用户与角色关系服务层
        /// </summary>
        private readonly IUserRoleService _userRoleService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userServices"></param>
        /// <param name="provinceServince"></param>
        /// <param name="cityService"></param>
        /// <param name="countryService"></param>
        public UserController(IConfiguration configuration,IMediator mediator,IUserService userServices, IProvinceService provinceServince,
            ICityService cityService, ICountryService countryService,
            IRoleService roleService, IUserRoleService userRoleService)
        {
            this.configuration = configuration;
            _mediator = mediator;
            _userServices = userServices;
            _provinceServices= provinceServince;
            _cityServices= cityService;
            _countryServices= countryService;
            _roleServices = roleService;
            _userRoleService = userRoleService;
        }
       
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="Uname"></param>
        /// <param name="Upwd"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]//不需要授权
        public async Task<ApiResult<string>> Logain(string Uname, string Upwd)
        {
            ApiResult<string> result=new ApiResult<string>();
            try
            {
                var list = await _userServices.Logain(Uname, Upwd);
                var plist = list.Userinfos;
                var rolelist = await _userRoleService.userRolesList(plist.userInfoId);
                var rids = rolelist.FirstOrDefault().roleId;
                //var rid = list.roleId;
                if(list!=null)
                {
                    result.Data = JwtNewString(list.Userinfos.userInfoId.ToString(), rids.ToString());
                }
                else
                {
                    result.Code = -1;
                    result.Message = "用户名密码不匹配";
                }
            }
            catch (Exception)
            {

                throw;
            }
           
           //// var plist=list.userin
           // var rolelist = await _userRoleService.GetUserRole(list.userInfoId);

           // if (list!=null)
           // {

           //     result.Data = JwtNewString(list.userInfoId.ToString(),rolelist.ToString());

           //     //var data = HttpContext.User;//获取当前登录用户的所有Token信息
           //     //List<int> Is = new List<int>();
           //     //var a = Is.Count;
           //     //var id = HttpContext.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;//获取sub的值
           //     //var rolesd = HttpContext.User.FindFirst(ClaimTypes.Role)?.Value;
           // }
           // else
           // {
           //     result.Code = -1;
           //     result.Message = "用户名或者密码错误";
           // }

            return result;

        }
        /// <summary>
        /// (从Token中取用户ID)2
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<UserInfo>>> GetUserFill()
        {
            ApiResult<List<UserInfo>> result = new ApiResult<List<UserInfo>>();
            try
            {
                var uid = Convert.ToInt32(HttpContext.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value);//获取sub的值
                result.Data=await _userServices.GetUserFill(uid);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }

            return result;
        }
        /// <summary>
        /// (从Token中取用户ID)1
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> GetUserAllss()
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                var uid = Convert.ToInt32(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);//获取sub的值
                result.Data = await _userServices.GetUserAlls(uid);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }

            return result;

            //var data = HttpContext.User;//获取当前登录用户的所有Token信息
            //List<int> Is = new List<int>();
            //var a = Is.Count;
           
        }
        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="uids"></param>
        ///    /// <param name="rid"></param>
        /// <returns></returns>
        private string JwtNewString(string uids,string rid)
        {
            //生成JWT
            //Header,选择签名算法
            var signingAlogorithm=SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uids),
                new Claim(ClaimTypes.Role,rid),
                //new Claim(ClaimTypes.UserData,"测试")
            };
            //Signature
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey=new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],
                audience: configuration["Authentication:Audience"],
                claims:claims,
                notBefore:DateTime.Now,
                expires:DateTime.UtcNow.AddDays(1),
                signingCredentials
                );
            //生成字符串token
            var tokenStr=new JwtSecurityTokenHandler().WriteToken(Token);
            return tokenStr;

        }
        /// <summary>
        /// 显示省份(利用IMediator)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Province>> GetProvincesList()
        {
          
            return await _mediator.Send(new ProvinceShowCommand());
        }
        /// <summary>
        /// 显示所在市(利用IMediator)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<City>> GetCities([FromQuery] CityShowCommand command)
        {
            return await _mediator.Send(command);
        }
        /// <summary>
        /// 显示所在县(利用IMediator)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Country>> GetCountries([FromQuery]CountryShowCommand command)
        {
           return await _mediator.Send(command);
        }
        /// <summary>
        /// 添加用户(利用IMediator)(取Token的值)
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddUser(UserCreateCommand command)
        {
           
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 删除用户信息(利用IMediator)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<int> DelUser([FromQuery]UserDeleteCommand command)
        {
            return await _mediator.Send(command);
        }
       
        /// <summary>
        /// 显示全部用户(利用IMediator)
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        [AllowAnonymous]//不需要授权
        public async Task<ApiResult<PageDto<UserDto>>> GetAll([FromQuery]UserShowCommand command)
        {
            ApiResult<PageDto<UserDto>> result = new ApiResult<PageDto<UserDto>>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }

            return result;
           
        }
        /// <summary>
        /// 反填用户信息(利用IMediator)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]

        public async Task<UserInfo> GetUserAll([FromQuery]UserGetIdCommand command)
        {

            return await _mediator.Send(command);
        }
        /// <summary>
        /// 修改用户信息(利用IMediator)
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateUserInfo(UserUpdateCommand command)
        {
            return await _mediator.Send(command);
        }
        /// <summary>
        /// （扩展方法）
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateUserInfoss()
        {
            //string numStr = "123a";
            //int num = numStr.ToInt();
            //int num1 = int.Parse(num);
            string idCard = "411024200202027767";
            string num = idCard.GetBirthDay();
            int num1 = int.Parse(num);
            return num1;



            
            
        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]//不需要授权
        [HttpGet]
        public async Task<List<UserInfo>> Getalls()
        {
           return await _userServices.Getalls();
        }


    }
}
